// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.callFunction({//查找用户by openid
    name: "model_user",
    data: {
      op: "select",
      key: "openid",
      value: event.openid
    }
  }).then(res => {//判断是否存在用户
    console.log(res.result.data.length);
    if (res.result.data.length != 0)//存在直接返回
      return res.result.data;
    else {//不存在则添加，并返回
      return cloud.callFunction({//添加
        name: "model_user",
        data: {
          op: "add",
          openid: event.openid,
          photo: event.photo,
          username: event.username,
          type: event.type,
          phone: event.phone
        }
      }).then(res => {//添加用户后，查询by _id并返回
        var _id = res.result._id;
        return cloud.callFunction({
          name: "model_user",
          data: {
            op: "select",
            key: "_id",
            value: _id
          }
        }).then(res => { return res.result.data; })
      })
    }
  })

}